#include "draw_tree.h"
#include "string.h"
#include "stdlib.h"

void draw_line(int start_line,int stop_line,char* memory,int start_column,int width)
{
	int i;
	char *line_memory = memory + (start_line*width)+start_column;
	memcpy(line_memory,"--",2);
	line_memory += 2;
	if (start_line == stop_line)
	{
		line_memory[0] = '-';
	}
	else
	{
		line_memory[0] = '|';
	}
	for (i = start_line+1;i<=stop_line;i++)
	{
		line_memory += width;
		line_memory[0] = '|';
	}
	line_memory++;
	memcpy(line_memory,"--",2);
}
int draw_one_node(draw_tree* tree,draw_tree_node* node,char *memory,int width,int depth)
{
	char temp_memory[10];
	int start_line = tree->column_depth[depth];
	int end_line;
	char *node_memory = memory + depth * ONE_NODE_WIDTH + width * tree->column_depth[depth];
	int line_num,i;
	if (0 == node->link_num)
	{
		line_num = node->key_num;
	}
	else
	{
		line_num = node->link_num-1;
	}
	memcpy(node_memory,"|---|",5);
	node_memory += width;
	if (1 == node->key_num)
	{
		for (i = 0;i<line_num;i++)
		{
			if (i == line_num/2)
			{
				sprintf(temp_memory,"|%3d|",node->pkey[0]);
				memcpy(node_memory,temp_memory,5);
			}
			else
			{
				memcpy(node_memory,"|   |",5);
			}
			node_memory += width;
			memcpy(node_memory,"|---|",5);
			node_memory += width;
		}
	}
	else
	{
		for (i = 0;i<line_num;i++)
		{
			sprintf(temp_memory,"|%3d|",node->pkey[i]);
			memcpy(node_memory,temp_memory,5);
			node_memory += width;
			memcpy(node_memory,"|---|",5);
			node_memory += width;
		}
	}
	tree->column_depth[depth] += ONE_NODE_LINE_GAP+ line_num*2 +1;
	for (i = 0;i<node->link_num;i++)
	{
		end_line = draw_one_node(tree,node->pnode[i],memory,width,depth+1);
		draw_line(start_line + i*2,end_line,memory,depth*10+5,width);
	}
	if (node->link_num>0)
	{
		tree->column_depth[depth] = tree->column_depth[depth+1];
	}
	return start_line;
}
void draw_one_tree(FILE * file,draw_tree* tree,char* memory,int width,int height)
{
	int i = 0;
	memset(tree->column_depth,0,sizeof(tree->column_depth));
	memset(memory,' ',sizeof(char)*width*height);
	draw_one_node(tree,tree->root,memory,width,0);
	for (i = 0;i<height;i++)
	{
		memory[width-1] = '\0';
		fprintf(file,"%s",memory);
		fprintf(file,"\n");
		memory += width;
	}
}